import { reqShopCarList } from "@/api/index.js";
import { reqRemveCart, reqChecked } from "@/api/index.js";
const state = {
  getShopCarList: [],
};
const mutations = {
  GETSHOPCARLIST(state, getShopCarList) {
    state.getShopCarList = getShopCarList;
  },
};
const actions = {
  async getShopCarList({ commit }) {
    let result = await reqShopCarList();
    if (result.code == 200) {
      commit("GETSHOPCARLIST", result.data);
    }
  },
  async removeCart({ commit }, skuId) {
    let result = await reqRemveCart(skuId);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("faile"));
    }
  },
  async getChecked({ commit }, { skuId, isChecked }) {
    let result = await reqChecked(skuId, isChecked);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("faile"));
    }
  },
  removeShopCart({ dispatch, getters }) {
    let PromiseAll = [];

    getters.getShopCarList.cartInfoList.forEach((item) => {
      let promise =
        item.isChecked == "1" ? dispatch("removeCart", item.skuId) : "";
      PromiseAll.push(promise);
    });
    return Promise.all(PromiseAll);
  },
  isAllCheckeds({ dispatch, state }, isChecked) {
    let promiseAll = [];
    state.getShopCarList[0].cartInfoList.forEach((item) => {
      let promise = dispatch("getChecked", { skuId: item.skuId, isChecked });
      promiseAll.push(promise);
    });
    return Promise.all(promiseAll);
  },
};
const getters = {
  getShopCarList(state) {
    return state.getShopCarList[0] || [];
  },
};

export default {
  state,
  mutations,
  actions,
  getters,
};
